package com.kitty.mina;

import com.kitty.game.role.model.Role;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.filter.ModuleCounterFilter;
import com.kitty.mina.session.SessionManager;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.session.IoSession;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 踢出非法
 *
 * @author StanWind
 * @create 2020 - 05 - 16 2:36 AM
 */
@Component
@Slf4j
public class ModuleCounterSchedule {

    /**
     * 启动三分钟后启动检测 30秒检查一次 踢出非法客户
     */
//    @Scheduled(initialDelay = 3 * 60 * 1000, fixedDelay = 30 * 1000)
//    public void process0() {
//        long timestamp = System.currentTimeMillis();
////        log.error("[MODULE_COUNTER] 开始检测非法用户 {}", timestamp);
//        SessionUtils.getSessionList().values().parallelStream().forEach(e -> {
//            ModuleCounter counter = ModuleCounterFilter.getCounter(e);
//            long connectedTime = timestamp - counter.getLoginTime();
//            //根据协议发送多样性判断是否进行心跳数检测
//            if (counter.getCounterMap().size() < ModuleCounterFilter.G_JUMP_HEARTBEAT_CHECK) {
//                int minHeartBeatCount = (int) Math.floor(connectedTime / 10000.0) - 1;
//                int heartBeatCount = counter.getCounterMap().getOrDefault(Modules.CMD_ECHO, new AtomicInteger(0)).get();
//                if (connectedTime >= ModuleCounterFilter.G_MAX_WAIT_TIME && heartBeatCount < minHeartBeatCount) {
//                    log.error("[MODULE_COUNTER] 心跳数不合法 {} < {} counter: {}", heartBeatCount, minHeartBeatCount,
//                            counter);
//                    disconnected(e);
//                }
//            }
//
//            if (counter.isChecked()) {
//                return;
//            }
//
//            if (connectedTime >= ModuleCounterFilter.G_MAX_WAIT_TIME) {
//                disconnected(e);
//            }
//        });
//    }

    public static void disconnected(IoSession session) {

        if(true){return;}

//        ModuleCounter counter = ModuleCounterFilter.getCounter(session);
        Role role = SessionUtils.getRoleBySession(session);
        String name = role == null ? "没有角色" : role.getName();
        String clientIP = ((InetSocketAddress) session.getRemoteAddress()).getAddress().getHostAddress();
        log.error("[MODULE_COUNTER] 超时踢出 {} 玩家信息: {} Counter数据: {}", clientIP, name);
        session.closeNow();
    }


    /**
     * 统计unchecked
     */
//    @Scheduled(fixedDelay = 10 * 1000)
//    public void process1() {
//        long count = SessionUtils.getSessionList().values().parallelStream()
//                .filter(e -> !ModuleCounterFilter.getCounter(e).isChecked()).count();
//        ModuleCounterFilter.G_UNCHECKED_PLAYER.set((int) count);
//    }
}
